package com.lsk.mps.backend.util;

import com.google.gson.Gson;

import java.util.*;

public final class ResponseUtil {
    private static final Gson GSON = SpringUtil.getBean(Gson.class);

    private static String doBuildResponse(int code, String message, Object data) {
        Map<String, Object> response = new HashMap<String, Object>();
        response.put("code", code);
        response.put("message", message);
        response.put("data", data);
        return GSON.toJson(response);
    }

    public static String buildSuccessResponse(Object data) {
        return doBuildResponse(200, "Success.", data);
    }

    public static String buildFailedResponse(Throwable t) {
        if (t instanceof StatusCode) {
            StatusCode statusCode = (StatusCode) t;
            return doBuildResponse(statusCode.getCode(), statusCode.getMessage(), null);
        } else {
            return doBuildResponse(500, t.getMessage(), null);
        }
    }
}
